package com.servlets;

import java.io.IOException;
import java.sql.SQLException;


import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.MessageService;

public class MessageListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		String message = request.getParameter("messagebox");
		String name = (String) session.getAttribute("nickname");
		
		ServletContext servletContext = this.getServletContext();
		WebApplicationContext webcontext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		MessageService messageService = (MessageService) webcontext.getBean("messageService");

		if (message != null && name != null) {
			try {
				messageService.addMessage(message, name);
			} catch (SQLException | NamingException e) {
				
				e.printStackTrace();
			}
				
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/chat.jsp");
			dispatcher.forward(request, response);
		} else {
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/start.jsp");
			dispatcher.forward(request, response);

		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

}
